package cn.edu.gzist.chapter07.config;

import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

// @Configuration
public class SecurityConfig2 {

    /**
	 * 默认用户名：user 密码：随机
	 * spring.security.user.name=
	 * spring.security.user.password=
	 * spring.security.user.roles=
	 */
	@Bean
	public UserDetailsService userDetailsService() {
		UserDetails user = User.builder().username("user").password("{noop}12345").roles("USER").build();
		return new InMemoryUserDetailsManager(user);
	}


    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception{
        // 所有路径需要认证
        httpSecurity.authorizeHttpRequests(authorize -> authorize.requestMatchers("/css/**","img/**","js/**").permitAll()
        .anyRequest().authenticated());
        // Sercurity允许使用iframe加载网页
        httpSecurity.headers(header -> header.frameOptions(frame -> frame.disable()));
        // 关闭csrf安全，logout可以使用get方法
        httpSecurity.csrf(csrf -> csrf.disable());
        // 1. 使用基本方式
        // httpSecurity.httpBasic(Customizer.withDefaults());
        // 2. 使用默认页面方式
        // httpSecurity.formLogin(Customizer.withDefaults());
        // 3. 自定义登录页面
        httpSecurity.formLogin(form -> form.loginPage("/login").successForwardUrl("/main").permitAll());
        return httpSecurity.build(); 
    }
    
}
